package net.newsmth.smthapp.android.helper;

import net.newsmth.smthapp.android.config.AppSettings;
import net.newsmth.smthapp.android.config.SmthConnection;
import net.newsmth.smthapp.android.model.Article;
import net.newsmth.smthapp.android.model.BBSThread;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Hatsune Miku on 5/9/14.
 */
public class BBSThreadHelperImpl implements BBSThreadHelper {
    private static int DEFAULT_ARTICLE_COUNT_PER_PAGE = 10;

    private AppSettings appSettings;
    private SmthConnection connection;
    private int countPerPage = DEFAULT_ARTICLE_COUNT_PER_PAGE;

    public BBSThreadHelperImpl() {
    }

    public BBSThreadHelperImpl(AppSettings settings, SmthConnection connection) {
        this.appSettings = settings;
        this.connection = connection;
    }

    @Override
    public List<Article> getArticles(BBSThread thread, long from) {
        return getArticles(thread, from, countPerPage);
    }

    @Override
    public void setCountPerPage(int count) {
        this.countPerPage = count;
    }

    @Override
    public List<Article> getAtricles(BBSThread thread, int page) {
        long from = (page * countPerPage);
        return getArticles(thread, from);
    }

    @Override
    public List<Article> getArticles(BBSThread thread, long from, long size) {
        List<Article> articleList = new ArrayList<Article>();

        JSONArray articles = this.connection.getThreadArticles(thread.getBoard(),
                thread.getId(), from, size, 0);

        if (articles != null) {
            int articlesCount = articles.length();

            for (int i = 0; i < articlesCount; i++) {
                try {
                    JSONObject articleObject = (JSONObject) articles.get(i);
                    Article article = Article.convertFromJson(articleObject);

                    if (article != null) {
                        articleList.add(article);
                    }
                } catch (JSONException ex) {

                }
            }
        }

        return articleList;
    }
}
